import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { toast } from '@/lib/toast-with-audio';
import { useTheme } from '@/hooks/useTheme';
import { messageApi } from '@/store/message';
import DetailDrawer from '@/components/DetailDrawer';
import type { Message, GetMessagesParams } from '@/types/message';

// 消息类型徽章组件
const MessageTypeBadge: React.FC<{ type: string }> = ({ type }) => {
  let className = '';
  
  switch (type) {
    case '系统通知':
      className = 'bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300';
      break;
    case '任务提醒':
      className = 'bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300';
      break;
    case '项目更新':
      className = 'bg-purple-100 dark:bg-purple-900 text-purple-700 dark:text-purple-300';
      break;
    case '缺陷提醒':
      className = 'bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300';
      break;
    case '团队协作':
      className = 'bg-yellow-100 dark:bg-yellow-900 text-yellow-700 dark:text-yellow-300';
      break;
    default:
      className = 'bg-gray-100 dark:bg-gray-700 text-gray-700 dark:text-gray-300';
  }
  
  return (
    <span className={`px-2 py-1 text-xs font-medium rounded-full ${className}`}>
      {type}
    </span>
  );
};

export default function Messages() {
  const { isDark } = useTheme();
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(false);
  const [unreadCount, setUnreadCount] = useState(0);
  
  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [totalMessages, setTotalMessages] = useState(0);
  
  // 筛选相关状态
  const [typeFilter, setTypeFilter] = useState('all');
  const [readFilter, setReadFilter] = useState('all');
  const [importantFilter, setImportantFilter] = useState('all');
  const [searchTerm, setSearchTerm] = useState('');
  
  // 抽屉相关状态
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [selectedMessage, setSelectedMessage] = useState<Message | null>(null);
  
  // 加载消息数据
  useEffect(() => {
    const loadMessages = async () => {
      setLoading(true);
      try {
        const params: GetMessagesParams = {
          page: currentPage,
          pageSize: pageSize
        };
        
        if (typeFilter !== 'all') {
          params.type = typeFilter;
        }
        
        if (readFilter !== 'all') {
          params.read = readFilter === 'read';
        }
        
        if (importantFilter !== 'all') {
          params.important = importantFilter === 'important';
        }
        
        if (searchTerm) {
          params.search = searchTerm;
        }
        
        const response = await messageApi.getMessages(params);
        setMessages(response.data);
        setTotalMessages(response.total);
        
        // 计算未读消息数量
        const unread = response.data.filter(msg => !msg.read).length;
        setUnreadCount(unread);
      } catch (error) {
        console.error('加载消息数据失败:', error);
        toast.error('加载消息数据失败');
      } finally {
        setLoading(false);
      }
    };

    loadMessages();
  }, [currentPage, pageSize, typeFilter, readFilter, importantFilter, searchTerm]);
  
  const handleMarkAsRead = async (messageId: number) => {
    try {
      await messageApi.markAsRead(messageId);
      toast.success('消息已标记为已读');
      // 重新加载消息数据
      setCurrentPage(1);
    } catch (error) {
      console.error('标记消息为已读失败:', error);
      toast.error('标记消息为已读失败');
    }
  };
  
  const handleMarkAllAsRead = async () => {
    try {
      await messageApi.markAllAsRead();
      toast.success('所有消息已标记为已读');
      // 重新加载消息数据
      setCurrentPage(1);
    } catch (error) {
      console.error('标记所有消息为已读失败:', error);
      toast.error('标记所有消息为已读失败');
    }
  };
  
  const handleDeleteMessage = async (messageId: number) => {
    try {
      await messageApi.deleteMessage(messageId);
      toast.success('消息已删除');
      // 重新加载消息数据
      setCurrentPage(1);
    } catch (error) {
      console.error('删除消息失败:', error);
      toast.error('删除消息失败');
    }
  };
  
  const handleDeleteAllRead = async () => {
    try {
      await messageApi.deleteAllRead();
      toast.success('已删除所有已读消息');
      // 重新加载消息数据
      setCurrentPage(1);
    } catch (error) {
      console.error('删除所有已读消息失败:', error);
      toast.error('删除所有已读消息失败');
    }
  };
  
  // 处理消息点击，打开抽屉显示详情
  const handleMessageClick = (message: Message) => {
    setSelectedMessage(message);
    setDrawerOpen(true);
    
    // 移除自动标记已读的逻辑，让用户手动决定是否标记已读
    // 如果消息未读，自动标记为已读
    // if (!message.read) {
    //   handleMarkAsRead(message.id);
    // }
  };
  
  // 关闭抽屉
  const handleCloseDrawer = () => {
    setDrawerOpen(false);
    setSelectedMessage(null);
  };
  
  return (
    <div>
      <div className="mb-6">
        <motion.div 
          className="mb-8"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
        <h1 className="text-2xl font-bold text-gray-800 dark:text-gray-100">消息中心</h1>
        <p className="text-gray-600 dark:text-gray-400 mt-1">
          您有 <span className="font-medium text-blue-600 dark:text-blue-400">{unreadCount}</span> 条未读消息
        </p>
        </motion.div>
      </div>
      
      {/* 工具栏 */}
      <motion.div 
        className="flex justify-between items-center mb-6"
        initial={{ opacity: 0, y: -20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.4 }}
      >
        <div className="flex items-center space-x-4">
          {/* 搜索框 */}
          <motion.div 
            className="relative"
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.4, delay: 0.1 }}
          >
            <input
              type="text"
              placeholder="搜索消息..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="py-2 pl-10 pr-4 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100 w-64"
            />
            <i className="fa-solid fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400"></i>
          </motion.div>
          
          <motion.select 
            className="py-2 pl-3 pr-8 border border-gray-300 dark:border-gray-600 rounded-lg appearance-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
            value={typeFilter}
            onChange={(e) => setTypeFilter(e.target.value)}
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.4, delay: 0.2 }}
          >
            <option value="all">全部类型</option>
            <option value="系统通知">系统通知</option>
            <option value="任务提醒">任务提醒</option>
            <option value="项目更新">项目更新</option>
            <option value="缺陷提醒">缺陷提醒</option>
            <option value="团队协作">团队协作</option>
          </motion.select>
          
          <motion.select 
            className="py-2 pl-3 pr-8 border border-gray-300 dark:border-gray-600 rounded-lg appearance-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
            value={readFilter}
            onChange={(e) => setReadFilter(e.target.value)}
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.4, delay: 0.3 }}
          >
            <option value="all">全部状态</option>
            <option value="unread">未读</option>
            <option value="read">已读</option>
          </motion.select>
          
          <motion.select 
            className="py-2 pl-3 pr-8 border border-gray-300 dark:border-gray-600 rounded-lg appearance-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
            value={importantFilter}
            onChange={(e) => setImportantFilter(e.target.value)}
            initial={{ opacity: 0, x: -20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.4, delay: 0.4 }}
          >
            <option value="all">全部重要度</option>
            <option value="important">重要消息</option>
            <option value="normal">普通消息</option>
          </motion.select>
        </div>
        
        <div className="flex items-center space-x-3">
          <motion.button 
            className="flex items-center bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded-lg transition-colors duration-300"
            onClick={handleMarkAllAsRead}
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.4, delay: 0.3 }}
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
          >
            <i className="fa-solid fa-check-double mr-2"></i>
            全部已读
          </motion.button>
          <motion.button 
            className="flex items-center bg-red-600 hover:bg-red-700 text-white py-2 px-4 rounded-lg transition-colors duration-300"
            onClick={handleDeleteAllRead}
            initial={{ opacity: 0, x: 20 }}
            animate={{ opacity: 1, x: 0 }}
            transition={{ duration: 0.4, delay: 0.4 }}
            whileHover={{ scale: 1.05 }}
            whileTap={{ scale: 0.95 }}
          >
            <i className="fa-solid fa-trash mr-2"></i>
            删除已读
          </motion.button>
        </div>
      </motion.div>
      
      {/* 消息列表 */}
      <motion.div 
        className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden"
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
      >
        <AnimatePresence>
          {loading ? (
            <motion.div 
              className="p-8 text-center"
              initial={{ opacity: 0, scale: 0.8 }}
              animate={{ opacity: 1, scale: 1 }}
              exit={{ opacity: 0, scale: 0.8 }}
              transition={{ duration: 0.3 }}
            >
              <motion.i 
                className="fa-solid fa-spinner text-2xl text-blue-500 mb-4"
                animate={{ rotate: 360 }}
                transition={{ duration: 1, repeat: Infinity, ease: "linear" }}
              ></motion.i>
              <p className="text-gray-500 dark:text-gray-400">加载中...</p>
            </motion.div>
          ) : messages.length === 0 ? (
            <motion.div 
              className="p-8 text-center"
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              transition={{ duration: 0.4 }}
            >
              <motion.i 
                className="fa-regular fa-bell text-4xl text-gray-300 dark:text-gray-600 mb-4"
                initial={{ scale: 0.5 }}
                animate={{ scale: 1 }}
                transition={{ type: "spring", stiffness: 200, delay: 0.1 }}
              ></motion.i>
              <motion.p 
                className="text-gray-500 dark:text-gray-400"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ delay: 0.2 }}
              >
                暂无消息
              </motion.p>
            </motion.div>
          ) : (
          <AnimatePresence>
            <div className="divide-y divide-gray-200 dark:divide-gray-700">
              {messages.map((message, index) => (
                <motion.div 
                  key={message.id} 
                  className={`p-6 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors cursor-pointer ${
                    !message.read ? 'bg-blue-50 dark:bg-blue-900/20' : ''
                  }`}
                  initial={{ opacity: 0, y: 20, scale: 0.95 }}
                  animate={{ opacity: 1, y: 0, scale: 1 }}
                  exit={{ opacity: 0, y: -20, scale: 0.95 }}
                  transition={{ 
                    duration: 0.4, 
                    delay: index * 0.05,
                    type: "spring",
                    stiffness: 100
                  }}
                  whileHover={{ y: -2 }}
                  layout
                  onClick={() => handleMessageClick(message)}
                >
                <div className="flex items-start justify-between">
                  <div className="flex-1">
                    <div className="flex items-center space-x-3 mb-2">
                      <MessageTypeBadge type={message.type} />
                      {message.important && (
                        <span className="px-2 py-1 bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300 text-xs font-medium rounded-full">
                          重要
                        </span>
                      )}
                      {!message.read && (
                        <span className="w-2 h-2 bg-blue-500 rounded-full"></span>
                      )}
                    </div>
                    
                    <h3 className="text-lg font-semibold text-gray-800 dark:text-gray-100 mb-2">
                      {message.title}
                    </h3>
                    
                    <p className="text-gray-600 dark:text-gray-400 mb-3">
                      {message.content}
                    </p>
                    
                    <div className="text-sm text-gray-500 dark:text-gray-400">
                      {message.time}
                    </div>
                  </div>
                  
                  <motion.div 
                    className="flex items-center space-x-2 ml-4"
                    initial={{ opacity: 0 }}
                    animate={{ opacity: 1 }}
                    transition={{ delay: 0.3 }}
                  >
                    {!message.read && (
                      <motion.button 
                        className="text-blue-600 dark:text-blue-400 hover:text-blue-900 dark:hover:text-blue-300 text-sm"
                        onClick={(e) => {
                          e.stopPropagation();
                          handleMarkAsRead(message.id);
                        }}
                        whileHover={{ scale: 1.1 }}
                        whileTap={{ scale: 0.9 }}
                      >
                        标记已读
                      </motion.button>
                    )}
                    <motion.button 
                      className="text-red-600 dark:text-red-400 hover:text-red-900 dark:hover:text-red-300 text-sm"
                      onClick={(e) => {
                        e.stopPropagation();
                        handleDeleteMessage(message.id);
                      }}
                      whileHover={{ scale: 1.1 }}
                      whileTap={{ scale: 0.9 }}
                    >
                      删除
                    </motion.button>
                  </motion.div>
                </div>
              </motion.div>
            ))}
          </div>
          </AnimatePresence>
        )}
        </AnimatePresence>
        
        {/* 分页组件 */}
        {messages.length > 0 && (
          <motion.div 
            className="flex justify-between items-center p-4 border-t border-gray-200 dark:border-gray-700"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            transition={{ duration: 0.3, delay: 0.2 }}
          >
            <div className="text-sm text-gray-500 dark:text-gray-400">
              显示第 {((currentPage - 1) * pageSize) + 1} 到 {Math.min(currentPage * pageSize, totalMessages)} 条，共 {totalMessages} 条消息
            </div>
            <div className="flex items-center space-x-2">
              <motion.button
                onClick={() => setCurrentPage(prev => Math.max(prev - 1, 1))}
                disabled={currentPage === 1}
                className="px-3 py-1 border border-gray-300 dark:border-gray-600 rounded-md disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 dark:hover:bg-gray-700"
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
              >
                上一页
              </motion.button>
              <span className="text-sm text-gray-700 dark:text-gray-300">
                第 {currentPage} 页，共 {Math.ceil(totalMessages / pageSize)} 页
              </span>
              <motion.button
                onClick={() => setCurrentPage(prev => Math.min(prev + 1, Math.ceil(totalMessages / pageSize)))}
                disabled={currentPage === Math.ceil(totalMessages / pageSize)}
                className="px-3 py-1 border border-gray-300 dark:border-gray-600 rounded-md disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50 dark:hover:bg-gray-700"
                whileHover={{ scale: 1.05 }}
                whileTap={{ scale: 0.95 }}
              >
                下一页
              </motion.button>
            </div>
          </motion.div>
        )}
      </motion.div>
      
      {/* 消息详情抽屉 */}
      <DetailDrawer 
        isOpen={drawerOpen}
        onClose={handleCloseDrawer}
        item={selectedMessage}
        type="message"
        onMarkAsRead={handleMarkAsRead} // 添加标记已读回调
      />
    </div>
  );
};